import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由组件----------
import reg from '@/views/reg.vue'
import login from '@/views/login.vue'
import Main from '@/views/main.vue'
import store from '@/store/'
import home from '@/views/home.vue'
import user from '@/views/info.vue'
import Avatar from '@/views/User/Avatar.vue'
import pwd from '@/views/User/ped.vue'
import artList from '@/views/Article/list.vue'
import ARTtwolist from '@/views/Article/Artlist.vue'
// 给Vue安装插件
Vue.use(VueRouter)
// 构造出router实力对象
const router = new VueRouter({
  // 路由规则数组
  routes: [
    { path: '/reg', component: reg },
    { path: '/login', component: login },
    {
      path: '/',
      component: Main,
      redirect: '/home',
      // 简写可以省略/
      children: [
        { path: 'home', component: home },
        { path: 'user-info', component: user },
        { path: 'user-avatar', component: Avatar },
        { path: 'user-pwd', component: pwd },
        { path: 'art-cate', component: artList },
        { path: 'art-list', component: ARTtwolist }
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    // 获取token 因为是js文件,不能通过this获取,所以导入store进行获取
    const token = store.state.user.token
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
// 导出router路由模块
export default router
